<template>
  <div>
    <ContentWrap>
      <div class="btnWrap routeHeader">
        <div>
          <el-button @click="saveData" v-hasPermi="['exceptionManagement:abnormal:save']" type="primary">保存</el-button>
          <el-button @click="close">关闭</el-button>
        </div>
      </div>
    </ContentWrap>

    <ContentWrap>
      <div class="content" :style="{ height: height + 'px', overflow: over }">
        <el-form
          class="-mb-5px"
          :model="queryParam"
          :inline="true"
          :rules="formRules"
          label-width="110px"
        >
          <el-form-item label="异常名称" prop="abnormalName">
            <el-input v-model="queryParam.abnormalName" class="!w-220px" />
          </el-form-item>
        </el-form>
        <el-form
          class="-mb-5px"
          :model="queryParam"
          :inline="true"
          :rules="formRules"
          label-width="110px"
        >
          <el-form-item label="状态" prop="dictAbnormalStatus">
            <el-select
              v-model="queryParam.dictAbnormalStatus"
              placeholder="请选择状态"
              clearable
              class="!w-220px"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <el-form
          class="-mb-5px"
          :model="queryParam"
          :inline="true"
          :rules="formRules"
          label-width="110px"
        >
          <el-form-item label="功能页面" prop="functionPageName">
            <div class="select-wrapper">
              <el-input v-model="queryParam.functionPageName" class="!w-220px" />
              <span class="search-icon" @click="openFunctionPage()">
                <Icon icon="ep:search" />
              </span>
            </div>
          </el-form-item>
        </el-form>
        <el-form
          class="-mb-5px"
          :model="queryParam"
          :inline="true"
          :rules="formRules"
          label-width="110px"
        >
          <el-form-item label="异常类型" prop="dictAbnormalType">
            <el-select
              v-model="queryParam.dictAbnormalType"
              placeholder="请选择异常类型"
              clearable
              class="!w-220px"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.DICT_ABNORMAL_TYPE)"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="title"><span class="red">*</span>异常条件</div>
        <div class="title">
          <el-table
          ref="multipleTableRef"
          border
          row-key="id"
          :data="queryParam.abnormalDetailsCreateReqVOS"
          @select-all="handleCheckBox"
          @select="handleCheckBox"
          width="80%"
        >
          <el-table-column align="left">
            <template #header>
              <span>并发关系</span>
            </template>
            <template #default="scope">
              <el-select
                v-model="scope.row.dictConcurrency"
                placeholder="请选择并发关系"
                required
                
              >
                <el-option
                  v-for="(dict, index) in getIntDictOptions(DICT_TYPE.DICT_CONCURRENCY)"
                  :key="index"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="left">
            <template #header>
              <span style="color: red">*</span>
              <span>数据状态</span>
            </template>
            <template #default="scope">
              <el-select
                v-model="scope.row.dataStatus"
                placeholder="请选择数据状态"
                required
                :disabled="!queryParam.functionPageName"
              >
                <el-option
                  v-for="(dict, index) in dataStatusOptions"
                  :key="index"
                  :label="dict.name"
                  :value="dict.name"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="left">
            <template #header>
              <span style="color: red">*</span>
              <span>数据字段1</span>
            </template>
            <template #default="scope">
              <el-select
                v-model="scope.row.dataField"
                placeholder="请选择数据字段1"
                required
                :disabled="!queryParam.functionPageName"
              >
                <el-option
                  v-for="(dict, index) in dataFieldoptions"
                  :key="index"
                  :label="dict.name"
                  :value="dict.name"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="left">
            <template #header>
              <span style="color: red">*</span>
              <span>比较方式</span>
            </template>
            <template #default="scope">
              <el-select
                v-model="scope.row.dictCompare"
                placeholder="请选择比较方式"
                required
              >
                <el-option
                  v-for="(dict, index) in getIntDictOptions(DICT_TYPE.DICT_COMPARE)"
                  :key="index"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="left">
            <template #header>
              <span>数据字段2</span>
            </template>
            <template #default="scope">
              <el-select
                v-model="scope.row.dataFieldSecond"
                placeholder="请选择数据字段2"
                required
                :disabled="!queryParam.functionPageName || scope.row.dictCompare == 20"
              >
                <el-option
                  v-for="(dict, index) in dataFieldoptions"
                  :key="index"
                  :label="dict.name"
                  :value="dict.name"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="left">
            <template #header>
              <span>阈值</span>
            </template>
            <template #default="scope">
              <el-input v-model="scope.row.threshold" />
            </template>
          </el-table-column>
          <el-table-column align="left">
            <template #header>
              <span>操作</span>
            </template>
            <template #default="scope">
              <el-button link type="primary" @click="addRow">新增行</el-button>
              <el-button link type="danger" @click="deleteRow(scope.$index)" v-if="scope.$index > 0"
                >删除行</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        </div>
        
        <div class="title"><span class="red">*</span>异常消息</div>
        <div class="btnWrap title" style="padding-bottom: 0">
          <div>
            <el-button @click="addDataFiled" type="primary">增加数据字段</el-button>
          </div>
        </div>
        <div class="title">
          <el-input
            v-model="queryParam.abnormalMessage"
            maxlength="200"
            :rows="4"
            resize="none"
            show-word-limit
            type="textarea"
          />
        </div>
        <div class="btnWrap title">
          <div>
            <span>通知角色</span>
            <el-button @click="openRole" style="margin-left: 10px" type="primary"
              >增加角色</el-button
            >
          </div>
        </div>
        <div class="title">
          <div class="card-container">
            <div
              class="card"
              v-for="(item, index) in roleList"
              :key="index"
              style="min-width: 100px; margin: 10px; display: inline-block"
            >
              <div class="card-content">
                {{ item.name }}
                <Icon class="mr-5px" icon="ep:close" @click="deleteCard(index)" />
              </div>
            </div>
          </div>
        </div>
        <div class="btnWrap title">
          <div>
            <span>通知用户</span>
            <el-button @click="openUser" style="margin-left: 10px" type="primary"
              >增加用户</el-button
            >
          </div>
        </div>
        <div class="title">
          <div class="card-container">
            <div
              class="card"
              v-for="(item, index) in userList"
              :key="index"
              style="min-width: 100px; margin: 10px; display: inline-block"
            >
              <div class="card-content">
                {{ item.nickname }}
                <Icon class="mr-5px" icon="ep:close" @click="deleteUserCard(index)" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </ContentWrap>
    <!-- 选择部件 -->
    <SelectComponent ref="formRefComponent" @success="addData" />
    <!-- 功能页面 -->
    <FunctionPage ref="functionPage" @success="getFunctionPage" />
    <!-- 数据字段 -->
    <dataFiled ref="dataField" @success="getDataField" />
    <!-- 增加角色 -->
    <roleListForm ref="roleListRef" @success="getRoleList" />
    <!-- 增加用户 -->
    <userListForm ref="userListRef" @success="getUserList" />
  </div>
</template>

<script lang="ts" setup>
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import * as AbnormalApi from '@/api/config/exceptionManagement/abnormal'
  import { useRoute } from 'vue-router'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import FunctionPage from './functionPage.vue'
  import dataFiled from './dataFiled.vue'
  import roleListForm from './roleList.vue'
  import userListForm from './userList.vue'
  const formRules = reactive({
    abnormalName: [{ required: true, message: '异常名称不能为空', trigger: 'blur' }],
    dictAbnormalStatus: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    functionPageId: [{ required: true, message: '功能页面不能为空', trigger: 'blur' }],
    dictAbnormalType: [{ required: true, message: '异常类型不能为空', trigger: 'blur' }],
    warehousePosition: [{ required: true, message: '仓库位置不能为空', trigger: 'blur' }],
    dictEnableStatus: [{ required: true, message: '仓库状态不能为空', trigger: 'blur' }]
  })
  const tagsViewStore = useTagsViewStore()
  const routes = useRouter() // 路由
  const route = useRoute()
  const passData = ref<any>([])
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗
  const queryParam = reactive({
    id: undefined,
    abnormalName: undefined,
    dictAbnormalStatus: undefined,
    functionPageId: undefined,
    dictAbnormalType: undefined,
    functionPageName: undefined,
    abnormalMessage: '',
    noticeRoleId: undefined,
    noticeRoleName: undefined,
    noticeUserId: undefined,
    noticeUserName: undefined,
    creatorName: undefined,
    createTime: undefined,
    dataFieldSecond: undefined,
    abnormalDetailsCreateReqVOS: [
      {
        abnormalId: undefined,
        dictConcurrency: undefined,
        dataStatus: undefined,
        dataField: undefined,
        dictCompare: undefined,
        dataFieldSecond: undefined,
        threshold: undefined,
        creatorName: undefined,
        id: undefined,
        createTime: undefined
      }
    ]
  })
  const { push } = useRouter()
  const loading = ref(true)
  const list = ref<any>([{}])
  const roleList = ref<any>([])
  const userList = ref<any>([])
  const dataFieldoptions = ref<any>([])
  const dataStatusOptions = ref<any>([
    {
      name: '全部'
    }
  ])
  const functionPage = ref()
  const openFunctionPage = () => {
    functionPage.value.open(passData.value)
  }
  //获取异常配置字段
  const setDataStatusOptions = ref<any>([])
  const getfield = async (id) => {
    setDataStatusOptions.value = []
    const data = await AbnormalApi.getfield(id)
    dataFieldoptions.value = data
    for (let i = 0; i < data.length; i++) {
      if (data[i].name.includes('状态')) {
        setDataStatusOptions.value.push(data[i])
      }
    }
    if (setDataStatusOptions.value.length > 0) {
      dataStatusOptions.value = setDataStatusOptions.value
    }
  }
  //删除行
  const deleteRow = (index: number) => {
    queryParam.abnormalDetailsCreateReqVOS.splice(index, 1)
  }
  //新增行
  const addRow = () => {
    let json = {
      abnormalId: undefined,
      dictConcurrency: undefined,
      dataStatus: undefined,
      dataField: undefined,
      dictCompare: undefined,
      dataFieldSecond: undefined,
      threshold: undefined,
      creatorName: undefined,
      id: undefined,
      createTime: undefined
    }
    queryParam.abnormalDetailsCreateReqVOS.push(json)
  }
  const getFunctionPage = async (data) => {
    passData.value = await data.list
    let datas = await data.list
    queryParam.functionPageName = datas[0].classC
    queryParam.functionPageId = datas[0].id
    for(let i = 0;i<queryParam.abnormalDetailsCreateReqVOS.length;i++){
      queryParam.abnormalDetailsCreateReqVOS[i].abnormalId = undefined
      queryParam.abnormalDetailsCreateReqVOS[i].dictConcurrency = undefined
      queryParam.abnormalDetailsCreateReqVOS[i].dataStatus = undefined
      queryParam.abnormalDetailsCreateReqVOS[i].dataField = undefined
      queryParam.abnormalDetailsCreateReqVOS[i].dictCompare = undefined
      queryParam.abnormalDetailsCreateReqVOS[i].dataFieldSecond = undefined
      queryParam.abnormalDetailsCreateReqVOS[i].threshold = undefined
      queryParam.abnormalDetailsCreateReqVOS[i].creatorName = undefined
      queryParam.abnormalDetailsCreateReqVOS[i].id = undefined
      queryParam.abnormalDetailsCreateReqVOS[i].createTime = undefined
    }
    queryParam.functionPageId
    getfield(queryParam.functionPageId)
  }
  const formRefComponent = ref()

  // const chooseComponent = () => {
  //   if (
  //     queryParam.orderNumber != undefined &&
  //     queryParam.orderNumber != null &&
  //     queryParam.productNumber != null &&
  //     queryParam.productNumber != undefined
  //   ) {
  //     formRefComponent.value.open(queryParam.orderNumber, queryParam.productNumber, list.value)
  //   } else {
  //     message.warning('订单号和产品编号都不能为空')
  //   }
  // }
  const addData = async (data) => {
    list.value = data.list
  }
  const dataField = ref()
  //增加数据字段
  const addDataFiled = () => {
    if (queryParam.functionPageId) {
      dataField.value.open(queryParam.functionPageId)
    } else {
      message.warning(t('请选择功能页面'))
    }
  }
  const getDataField = (data) => {
    queryParam.abnormalMessage += '{' + data.list[0].name + '}'
  }
  const deleteCard = (index) => {
    roleList.value.splice(index, 1)
  }
  const deleteUserCard = (index) => {
    userList.value.splice(index, 1)
  }
  const roleListRef = ref()
  //增加角色
  const openRole = () => {
    roleListRef.value.open(roleList.value)
  }
  const getRoleList = async (data) => {
    console.log(data)
    roleList.value = await data.list
    let datas = await data.list
    queryParam.noticeRoleName = datas.map((item) => item.name).join(',')
    queryParam.noticeRoleId = datas.map((item) => item.id).join(',')
    console.log(queryParam.noticeRoleId)
    console.log(queryParam.noticeRoleName)
  }
  const userListRef = ref()
  //增加用户
  const openUser = () => {
    userListRef.value.open(userList.value)
  }
  const getUserList = async (data) => {
    userList.value = await data.list
    console.log(userList.value)
    let datas = await data.list
    queryParam.noticeUserName = datas.map((item) => item.nickname).join(',')
    queryParam.noticeUserId = datas.map((item) => item.id).join(',')
  }

  // const deleteRow = (index: number) => {
  //   list.value.splice(index, 1)
  // }

  //必填校验
  const check = async () => {
    if (!queryParam.abnormalName) {
      message.warning(t('异常名称不能为空'))
      return false
    }
    if (queryParam.dictAbnormalStatus == undefined) {
      message.warning(t('状态不能为空'))
      return false
    }
    if (!queryParam.functionPageName) {
      message.warning(t('功能页面不能为空'))
      return false
    }
    if (!queryParam.dictAbnormalType) {
      message.warning(t('异常类型不能为空'))
      return false
    }
    if (queryParam.abnormalDetailsCreateReqVOS.length > 1) {
      for (let i = 1; i < queryParam.abnormalDetailsCreateReqVOS.length; i++) {
        if (queryParam.abnormalDetailsCreateReqVOS[i].dictConcurrency == undefined) {
          message.warning(t('请选择并发关系'))
        }
        return false
      }
    }
    for (let i = 0; i < queryParam.abnormalDetailsCreateReqVOS.length; i++) {
      console.log(queryParam.abnormalDetailsCreateReqVOS[i].dictCompare)
      if (
        queryParam.abnormalDetailsCreateReqVOS[i].dictCompare == 10 ||
        queryParam.abnormalDetailsCreateReqVOS[i].dictCompare == 30
      ) {
        if (!queryParam.abnormalDetailsCreateReqVOS[i].dataField) {
          message.warning(t('请选择请选择数据字段1'))
          return false
        }
        if (!queryParam.abnormalDetailsCreateReqVOS[i].dataFieldSecond) {
          message.warning(t('请选择请选择数据字段2'))
          return false
        }
      }
      if (queryParam.abnormalDetailsCreateReqVOS[i].dictCompare == 20) {
        if (queryParam.abnormalDetailsCreateReqVOS[i].dataFieldSecond) {
          message.warning(t('数据字段2不可选择'))
          return false
        }
      }
    }
    if (!queryParam.abnormalMessage) {
      message.warning(t('异常消息不能为空'))
      return false
    }
    return true
  }
  /**保存 */
  const saveData = async () => {
    const isFlag = await check()
    console.log(isFlag)

    loading.value = true
    try {
      const isFlag = await check()
      if (isFlag) {
        await AbnormalApi.createAbnormal(queryParam)
        close()
      }
    } finally {
      loading.value = false
    }
  }
  /**关闭 */
  const close = () => {
    tagsViewStore.delView(routes.currentRoute.value)
    push('/config/config/exceptionManagement/abnormal')
  }
  //获取详情
  const getDetail = async (id) => {
    const data = await AbnormalApi.getAbnormal(id)
    queryParam.id = data.id
    queryParam.abnormalName = data.abnormalName
    queryParam.dictAbnormalStatus = data.dictAbnormalStatus
    queryParam.functionPageId = data.functionPageId
    queryParam.dictAbnormalType = data.dictAbnormalType
    queryParam.functionPageName = data.functionPageName
    queryParam.abnormalMessage = data.abnormalMessage
    queryParam.noticeRoleId = data.noticeRoleId
    queryParam.noticeRoleName = data.noticeRoleName
    queryParam.noticeUserId = data.noticeUserId
    queryParam.noticeUserName = data.noticeUserName
    queryParam.creatorName = data.creatorName
    queryParam.createTime = data.createTime
    queryParam.dataFieldSecond = data.dataFieldSecond
    queryParam.abnormalDetailsCreateReqVOS = data.abnormalDetailsRespVOS
    let rolesName = queryParam.noticeRoleName.split(',')
    let rolesId = queryParam.noticeRoleId.split(',')
    console.log(rolesName, rolesId)
    roleList.value = rolesName.map((name, index) => ({
      name: name,
      id: rolesId[index]
    }))
    let userName = queryParam.noticeUserName.split(',')
    let userId = queryParam.noticeUserId.split(',')
    console.log(userName)
    console.log(userId)
    userList.value = userName.map((name, index) => ({
      nickname: name,
      id: userId[index]
    }))
    console.log(userList.value)
    loading.value = false
  }
  // 初始化
  const height = ref(0)
  onMounted(async () => {
    height.value = document.body.clientHeight - 230
    if (route.query.id) {
      getDetail(route.query.id)
    }
  })
</script>
<style lang="scss" scoped>
  .contentView {
    padding: 10px;
    background: #fff;
  }
  .tableView {
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
      cursor: default;
      .el-input__inner {
        cursor: default !important;
        text-align: center;
      }
    }
  }
  .btnWrap {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .el-table .custom-header::before {
    content: '*';
    color: red;
    margin-right: 4px; /* 根据需要调整小红星与字段的位置 */
  }
  .dropdown-width {
    width: 50px !important;
  }
  :deep(.el-form .el-input, .el-form .el-input__wrapper, .el-form .el-textarea) {
    width: 100% !important;
  }
  .select-wrapper {
    display: flex;
    align-items: center;
  }

  .search-icon {
    margin-left: -24px; /* 这里的 -24px 是根据 Icon 的宽度进行调整的 */
    cursor: pointer;
    margin-top: 5px;
  }
  .red {
    color: red;
  }
  .title {
    padding: 10px 33px;
  }
  .card-content {
    border: 1px solid #37bda5;
    background-color: #e2f5f2;
    padding: 0 0 0 10px;
    border-radius: 5px;
    line-height: 30px;
  }
  .mr-5px {
    color: red;
    margin-right: 0;
    margin-left: 16px;
    margin-top: 5px;
  }
  .content {
    overflow-y: scroll;
  }
</style>
